package com.lagou.rpc;

import com.lagou.boot.ConsumerBoot;
import com.lagou.configBean.ZkClient;
import com.lagou.handler.UserClientHandler;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import java.util.Map;

/**
 * @author ascetic
 * @version 1.0
 * @ClassName FastFindLink
 * @Description TODO
 * @date 2020-07-04 12:43
 */
public class FastFindLink implements FindLinkHandler {

    @Override
    public String findLink(Map<String, UserClientHandler> tcpLink) throws Exception {
        System.out.println("最快响应服务器方法");
        CuratorFramework client = ZkClient.getZKClient();
        Long time = System.currentTimeMillis();
        String serverIp = null;
        for (String key : tcpLink.keySet()) {
            Stat state = client.checkExists().forPath(ConsumerBoot.serverName+key+":"+"lastAckTime");
            if(state != null){
                byte[] bytes = client.getData().forPath(ConsumerBoot.serverName+key);
                Long value = Long.valueOf(new String(bytes));
                if(value < time){
                    time = value;
                    serverIp = key;
                }

            }
        }
        return serverIp;
    }

}